//
//  KeRenRequestTool.m
//  KEREN
//
//  Created by chenliang on 2023/8/8.
//

#import "KeRenRequestTool.h"
#import "NSDictionary+Expand.h"
typedef void(^CommunicateDeviceConfigCheckBlock)(BOOL update);
@implementation KeRenRequestTool

+(void)devicePowerChange:(DeviceInfo *)deviceInfo status:(NSInteger)status bleSuccess:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:deviceInfo.sn_code];
    if([deviceInfo is4GDevice]){
        if(p_state == CBPeripheralStateConnected){
            AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
            if(deviceInfo.online_status == 0 || netManger.networkReachabilityStatus == 0){
                //通过蓝牙发送数据
                [self sendPowerDataByBLE:status success:success failure:failure];
            }else{
                //通过HTTP发送数据,如果失败用蓝牙重发一次
                [self sendPowerDataByNetwork:status failWithBLE:YES success:success failure:failure];
            }
        }else{
            //通过HTTP发送数据,如果失败不会用蓝牙重发
            [self sendPowerDataByNetwork:status failWithBLE:NO success:success failure:failure];
        }
    }else{
        //通过蓝牙发送数据
        if(p_state == CBPeripheralStateConnected){
           [self sendPowerDataByBLE:status success:success failure:failure];
        }else{
          DDLogInfo(@"=======bleConnected characteristic is: 016");
          [[KRAlartManager shareInstance] showAlert:@"蓝牙还未连上"];
        }
  }
}

+(void)deviceTruck:(DeviceInfo *)deviceInfo bleSuccess:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:deviceInfo.sn_code];
    if([deviceInfo is4GDevice]){
        if(p_state == CBPeripheralStateConnected){
            AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
            if(deviceInfo.online_status == 0  || netManger.networkReachabilityStatus == 0){
                [self sendTruckByBLE:success failure:failure];
            }else{
                [self sendTruckByNet:YES success:success failure:failure];
            }
        }else{
            [self sendTruckByNet:NO success:success failure:failure];
        }
    }else{
        //通过蓝牙发送数据
        if(p_state == CBPeripheralStateConnected){
            [self sendTruckByBLE:success failure:failure];
        }else{
          [[KRAlartManager shareInstance] showAlert:@"蓝牙还未连上"];
        }
    }
}

+(void)deviceSearch:(DeviceInfo *)deviceInfo bleSuccess:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:deviceInfo.sn_code];
    if([deviceInfo is4GDevice]){
        if(p_state == CBPeripheralStateConnected){
            AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
            if(deviceInfo.online_status == 0 || netManger.networkReachabilityStatus == 0){
                [self sendSearchByBLE:success failure:failure];
            }else{
                [self sendSearchByNET:YES success:success failure:failure];
            }
        }else{
            [self sendSearchByNET:NO success:success failure:failure];
        }
    }else{
        //通过蓝牙发送数据
        if(p_state == CBPeripheralStateConnected){
            [self sendSearchByBLE:success failure:failure];
        }else{
          [[KRAlartManager shareInstance] showAlert:@"蓝牙还未连上"];
        }
    }
}

//结束寻车
+(void)deviceEndSearch:(DeviceInfo *)deviceInfo bleSuccess:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:deviceInfo.sn_code];
    if([deviceInfo is4GDevice]){ //先保证http发送数据，再加上BLE补充
        if(p_state == CBPeripheralStateConnected){
            AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
            if(deviceInfo.online_status == 0 || netManger.networkReachabilityStatus == 0){
                [self sendEndSearchByBLE:success failure:failure];
            }else{
                [self sendEndSearchByNET:YES success:success failure:failure];
            }
        }else{
            [self sendEndSearchByNET:NO success:success failure:failure];
        }
    }else{ //通过蓝牙发送数据
        if(p_state == CBPeripheralStateConnected){
            [self sendEndSearchByBLE:success failure:failure];
        }else{
          [[KRAlartManager shareInstance] showAlert:@"蓝牙还未连上"];
        }
    }
}

+(void)deviceLockDistance:(DeviceInfo *)deviceInfo gear:(int)gear bleSuccess:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:deviceInfo.sn_code];
    if([deviceInfo is4GDevice]){
        if(p_state == CBPeripheralStateConnected){
            AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
            if(deviceInfo.online_status == 0 || netManger.networkReachabilityStatus == 0){
                [self deviceLockDistanceByBLE:gear success:success failure:failure];
            }else{
                [self deviceLockDistanceByNet:deviceInfo gear:gear success:success failure:failure];
            }
        }else{
            if(deviceInfo.online_status == 0){
               [[KRAlartManager shareInstance] showErrorAlert:@"车辆已离线"];
                return;
            }
            [self deviceLockDistanceByNet:deviceInfo gear:gear success:success failure:failure];
        }
    }else{
        if(p_state == CBPeripheralStateConnected){
            [self deviceLockDistanceByBLE:gear success:success failure:failure];
        }else{
          [[KRAlartManager shareInstance] showAlert:@"蓝牙还未连上"];
        }
    }
}

+(void)deviceVibrateSensitivity:(DeviceInfo *)deviceInfo gear:(int)gear bleSuccess:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:deviceInfo.sn_code];
    if([deviceInfo is4GDevice]){
        if(p_state == CBPeripheralStateConnected){
            AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
            if(deviceInfo.online_status == 0 || netManger.networkReachabilityStatus == 0){
                [self deviceVibrateSensitivityByBLE:gear success:success failure:failure];
            }else{
                [self deviceVibrateSensitivityByNet:deviceInfo gear:gear success:success failure:failure];
            }
        }else{
            if(deviceInfo.online_status == 0){
               [[KRAlartManager shareInstance] showErrorAlert:@"车辆已离线"];
                return;
            }
            [self deviceVibrateSensitivityByNet:deviceInfo gear:gear success:success failure:failure];
        }
    }else{
        if(p_state == CBPeripheralStateConnected){
            [self deviceVibrateSensitivityByBLE:gear success:success failure:failure];
        }else{
          [[KRAlartManager shareInstance] showAlert:@"蓝牙还未连上"];
        }
    }
}

+(void)deviceLockedStatusChange:(DeviceInfo *)deviceInfo status:(BOOL)status  success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:deviceInfo.sn_code];
    if([deviceInfo is4GDevice]){
        if(p_state == CBPeripheralStateConnected){
            AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
            if(deviceInfo.online_status == 0 || netManger.networkReachabilityStatus == 0){
                [self deviceLockStatusChangeByBLE:deviceInfo success:success failure:failure];
            }else{
                [self deviceLockStatusChangeByNet:deviceInfo success:success failure:failure];
            }
        }else{
            if(deviceInfo.online_status == 0){
               [[KRAlartManager shareInstance] showErrorAlert:@"车辆已离线"];
                return;
            }
            [self deviceLockStatusChangeByNet:deviceInfo success:success failure:failure];
        }
    }else{
        [self deviceLockStatusChangeByBLE:deviceInfo success:success failure:failure];
    }
}

+(void)otaCheckVersionAndUpgrade:(DeviceInfo *)deviceInfo{
    WEAKSELF
    if(deviceInfo.sn_code.length > 0){
        NSDictionary *parameters = @{@"sn_code":deviceInfo.sn_code};
        [NetworkingTool POST:ota_checkVersion parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            if([response[@"code"] intValue] == 0){
                if([response[@"data"] isKindOfClass:[NSDictionary class]]){
                    NSDictionary *dict = response[@"data"];
                    if([dict[@"release_type"] intValue] == 1){
                        [[KRAlartManager shareInstance] showTipsAlertWithTitle:@"温馨提示" decTitle:@"检测到新固件版本,请升级" andOkBtnText:@"确认" sucessBlock:^(BOOL isSucess){
                            if(dict[@"tactics_id"]){
                                [weakSelf getOtaUpgrade:deviceInfo status:1 andtacticsId:[dict[@"tactics_id"] intValue]];
                            }
                        }];
                    }
                }
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
            
        }];
    }
}

+(void)deviceConfigQuery:(DeviceInfo *)deviceInfo configResult:(CommunicateDeviceConfigSuccess)block{
    NSString *where = [NSString stringWithFormat:@"where %@=%@ ",bg_sqlKey(@"device_type_id"),bg_sqlValue(@(deviceInfo.device_type_id))];
    NSArray *array = [DeviceConfigData bg_find:nil where:where];
    if(array.count > 0){
        WEAKSELF
        DeviceConfigData *configData = array.lastObject;
        [self deviceConfigCheck:configData result:^(BOOL update) {
            if(update){
                [weakSelf deviceConfigNet:deviceInfo configResult:block];
            }else{
                DeviceConfig *deviceConfig = [DeviceConfig parseFromJsonString:configData.func_config];
                if(block) block(deviceConfig);
            }
        }];
    }else{
        [self deviceConfigNet:deviceInfo configResult:block];
    }
}


//private
+(void)sendPowerDataByBLE:(NSInteger)type success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    WEAKSELF
    [HABleManager setDeviceIsOpen:type withCmd:^(HABleModel * _Nonnull bleModel) {
        if([bleModel.Cmd isEqualToString:@"61"] && [bleModel step_status] == 1 && ([bleModel.magic isEqualToString:@"fd"] ||[bleModel.magic isEqualToString:@"FD"])){
            if(success) success(NO,YES);
        }else{
            if(success) success(NO,NO);
        }
    }];
}
//private
+(void)sendPowerDataByNetwork:(NSInteger)type failWithBLE:(BOOL)failWithBLE success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    WEAKSELF
    [NetworkingTool POST:Device_send_cmd parameters:@{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"cmd":@(type)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(success) success(YES,YES);
        }else{
            if(failWithBLE){
                [weakSelf sendPowerDataByBLE:type success:success failure:failure];
            }else{
                if(success) success(YES,NO);
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(failure) failure(YES);
    }];
}

//private
+(void)sendTruckByBLE:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    [HABleManager bleOpenTrunk:^(HABleModel * _Nonnull bleModel) {
        if([bleModel step_status] == 1){
            if(success) success(NO,YES);
        }else{
            if(failure) failure(NO);
        }
    }];
}
//private
+(void)sendTruckByNet:(BOOL)failWithBLE success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    WEAKSELF
    [NetworkingTool POST:Device_send_cmd parameters:@{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"cmd":@(4)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(success) success(YES,YES);
        }else{
            if(failWithBLE){
                [weakSelf sendTruckByBLE:success failure:failure];
            }else{
                DDLogInfo(@"=========sendTruckByNet failure");
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(failWithBLE){
            [weakSelf sendTruckByBLE:success failure:failure];
        }else{
            if(failure) failure(YES);
        }
    }];
}


//private
+(void)sendSearchByBLE:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    [HABleManager bleStarefoundDevice:^(HABleModel * _Nonnull bleModel) {
    
    }];
    if(success) success(NO,YES);
}
//private
+(void)sendSearchByNET:(BOOL)failWithBLE success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    WEAKSELF
    [NetworkingTool POST:Device_signal_send_msg parameters:@{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"play_voice":@(8)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(success) success(YES,YES);
        }else{
            if(failWithBLE){
                [weakSelf sendSearchByBLE:success failure:failure];
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(failWithBLE){
            [weakSelf sendSearchByBLE:success failure:failure];
        }
    }];
}


//private
+(void)sendEndSearchByBLE:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    [HABleManager bleEndfoundDevice:^(HABleModel * _Nonnull bleModel) {
    }];
}

//private
+(void)sendEndSearchByNET:(BOOL)failWithBLE success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    WEAKSELF
    [NetworkingTool POST:Device_signal_send_msg parameters:@{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"play_voice":@(-1)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(success) success(YES,YES);
        }else{
            if(failWithBLE){
                [weakSelf sendEndSearchByBLE:success failure:failure];
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(failWithBLE){
            [weakSelf sendEndSearchByBLE:success failure:failure];
        }
    }];
}


//private
+(void)deviceLockDistanceByNet:(DeviceInfo *)deviceInfo gear:(int)gear success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    NSDictionary *ebike_set = @{@"ebike_id":@(deviceInfo.Id),@"senseless_unlock":@(gear)};
    [NetworkingTool POST:Device_signal_toggle parameters:ebike_set isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(success) success(YES,YES);
        }else{
            if(failure) failure(YES);
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(failure) failure(YES);
    }];
}
//private
+(void)deviceLockDistanceByBLE:(int)gear success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    [HABleManager bleUnlockDistance:gear withCmd:^(HABleModel * _Nonnull bleModel) {
        if([bleModel step_status] == 1){
            if(success) success(NO,YES);
        }else{
            if(failure) failure(NO);
        }
    }];
}

//private
+(void)deviceVibrateSensitivityByNet:(DeviceInfo *)deviceInfo gear:(int)gear success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    NSDictionary *ebike_set = @{@"ebike_id":@(deviceInfo.Id),@"vibration_sensitivity":@(gear)};
    [NetworkingTool POST:Device_signal_toggle parameters:ebike_set isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(success) success(YES,YES);
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(failure) failure(YES);
    }];
}

//private
+(void)deviceVibrateSensitivityByBLE:(int)gear success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    [HABleManager bleVibrateSensitive:gear withCmd:^(HABleModel * _Nonnull bleModel) {
        if([bleModel step_status] == 1){
            if(success) success(NO,YES);
        }else{
            if(failure) failure(NO);
        }
    }];
}


//private
+(void)deviceLockStatusChangeByNet:(DeviceInfo *)deviceInfo success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    int type = (deviceInfo.lock_status == 1) ? 2 : 3;
    [NetworkingTool POST:Device_send_cmd parameters:@{@"ebike_id":@(deviceInfo.Id),@"cmd":@(type)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(success) success(YES,YES);
        }else{
            if(failure) failure(YES);
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(failure) failure(YES);
    }];
}

//private
+(void)deviceLockStatusChangeByBLE:(DeviceInfo *)deviceInfo success:(CommunicateSuccess)success failure:(CommunicateFailure)failure{
    int type = (deviceInfo.lock_status == 1) ? 1 : 0;
    [HABleManager bleLockStatusChange:type withCmd:^(HABleModel * _Nonnull bleModel) {
        if([bleModel step_status] == 1){
            if(success) success(NO,YES);
        }else{
            if(failure) failure(NO);
        }
    }];
}

//private
+ (void)getOtaUpgrade:(DeviceInfo *)deviceInfo status:(int)status andtacticsId:(int)tacticsId{
    //ota_upgrade
    NSDictionary *parameters = @{@"sn_code":deviceInfo.sn_code,@"status":@(status),@"tactics_id":@(tacticsId)};
    [NetworkingTool POST:ota_upgrade_url parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

//private 检查设备配置是否有更新
+(void)deviceConfigCheck:(DeviceConfigData *)configData result:(CommunicateDeviceConfigCheckBlock)result{
    NSDictionary *parameters = @{@"device_type_id":@(configData.device_type_id),@"updated_at":@(configData.timeStamp)};
    [NetworkingTool POST:device_config_check parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            NSDictionary *data = [((NSDictionary *)response) dictForDict:@"data"];
            int is_updated =[data intForDict:@"is_updated"];
            if(result) result(is_updated);
        }else{
            if(result)  result(NO);
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(result)  result(NO);
    }];
}
//private
+(void)deviceConfigNet:(DeviceInfo *)deviceInfo configResult:(CommunicateDeviceConfigSuccess)block{
    NSDictionary *parameters = @{@"id":@(deviceInfo.device_type_id)};
    [NetworkingTool POST:device_config_query parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            long long timeStamp = [[NSDate date] timeIntervalSince1970];
            NSDictionary *data = [((NSDictionary *)response) dictForDict:@"data"];
            NSString *func_config =[data stringForDict:@"func_config"];
            DeviceConfigData *configData = [[DeviceConfigData alloc] init];
            configData.device_type_id = deviceInfo.device_type_id;
            configData.func_config = func_config;
            configData.timeStamp = timeStamp;
            [configData bg_saveOrUpdate];
            DeviceConfig *deviceConfig = [DeviceConfig parseFromJsonString:func_config];
            if(block) block(deviceConfig);
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        if(block)  block(nil);
    }];
}

+(void)deviceElectrict:(DeviceInfo *)deviceInfo bleSuccess:(CommunicateSuccess)success failure:(CommunicateFailure)failure{

}
@end
